'use strict';

module.exports = () => {
  // 验证用户是否登录
  return async function (ctx, next) {
    ctx.locals.currentUser = null;

    const user = ctx.session.user;

    if (!user) {
      return await next();
    }

    const [ctxUser, count] = await Promise.all([
      ctx.service.userSvc.getUserById(user.id),
      ctx.service.messageSvc.getMessagesCount(user.id)
    ]);

    ctx.user = ctxUser;
    user.messages_count = count;
    ctx.locals.currentUser = user;
    await next();
  };
};
